<template>
    <div class="post-detail">
        <button class="back-button" @click="goBack">
            <i class="fas fa-arrow-left"></i>
            < </button>
                <div class="post-content-container">
                    <h1>{{ post.title }}</h1>
                    <p>作者：{{ post.author }}</p>
                    <p>日期：{{ formatDate(post.date) }}</p>
                    <div class="post-content">
                        {{ post.content }}
                    </div>
                    <div class="post-footer">
                        <span>点赞：{{ post.likes }}</span>
                        <span>评论：{{ post.comments }}</span>
                        <button v-if="isAuthor" @click="deletePost" class="delete-button">
                            <i class="fas fa-trash"></i> 删除帖子
                        </button>
                    </div>
                </div>
    </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const route = useRoute();
const router = useRouter();
const post = ref({});
const currentUser = ref(null);

const loadPost = async () => {
  try {
    const response = await fetch(`http://localhost:3000/posts/${route.params.postId}`);
    if (!response.ok) {
      router.push('/not-found');
      return;
    }
    post.value = await response.json();
    
    // 获取当前用户信息
    const token = localStorage.getItem('token');
    if (token) {
      const userResponse = await fetch('http://localhost:3000/profile', {
        headers: {
          'Authorization': token
        }
      });
      if (userResponse.ok) {
        currentUser.value = await userResponse.json();
      }
    }
  } catch (error) {
    console.error('加载帖子失败:', error);
    router.push('/not-found');
  }
};

// 计算属性，检查当前用户是否是帖子的作者
const isAuthor = computed(() => {
  return currentUser.value && currentUser.value.username === post.value.author;
});

// 删除帖子
const deletePost = async () => {
  if (!confirm('确定要删除这个帖子吗？此操作不可撤销。')) {
    return;
  }
  
  try {
    const token = localStorage.getItem('token');
    if (!token) {
      router.push('/login');
      return;
    }
    
    const response = await fetch(`http://localhost:3000/posts/${route.params.postId}`, {
      method: 'DELETE',
      headers: {
        'Authorization': token,
        'Content-Type': 'application/json' // 明确指定内容类型
      },
      credentials: 'include' // 如果需要发送凭据
    });
    
    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(errorData.error || '删除帖子失败');
    }
    
    // 删除成功后跳转回论坛页面
    router.push('/forum');
  } catch (error) {
    console.error('删除帖子失败:', error);
    alert(error.message || '删除帖子失败，请重试');
  }
};

onMounted(() => {
  loadPost();
});

const formatDate = (dateString) => {
  const date = new Date(dateString);
  return date.toLocaleDateString() + ' ' + date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
};

const goBack = () => {
  router.push('/forum');
};
</script>

<style scoped>
.post-detail {
    background-color: #fffaf5; /* 柔和的米白色背景 */
    min-height: 100vh;
    padding: 2rem;
    font-family: 'Helvetica Neue', Arial, sans-serif;
}

.delete-button {
  background: #f8d7da;
  color: #721c24;
  border: none;
  border-radius: 4px;
  padding: 0.5rem 1rem;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-left: auto;
}

.delete-button:hover {
  background: #f1b0b7;
}

.post-footer {
  display: flex;
  gap: 1.5rem;
  align-items: center;
  margin-top: 2rem;
  padding-top: 1.5rem;
  border-top: 2px solid #f0e2d4;
}

.back-button {
    background: #f5e6d3; /* 浅米色按钮背景 */
    color: #6d4c3d; /* 深棕色文字 */
    border: 1px solid #e0d1c1;
    border-radius: 20px;
    padding: 0.5rem 1.5rem;
    cursor: pointer;
    transition: all 0.3s ease;
    margin-bottom: 1.5rem;
    box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.back-button:hover {
    background: #e8d5c4; /* 稍深的米色 */
    transform: translateY(-1px);
}

.post-content-container {
    max-width: 800px;
    margin: 0 auto;
    background: white;
    border-radius: 15px;
    padding: 2.5rem;
    box-shadow: 0 4px 12px rgba(0,0,0,0.08);
}

h1 {
    color: #5a4132; /* 温暖的咖啡色 */
    font-size: 2.2rem;
    margin-bottom: 1.2rem;
    border-bottom: 2px solid #f0e2d4;
    padding-bottom: 1rem;
}

p {
    color: #7f6b5e; /* 柔和的灰褐色 */
    margin-bottom: 0.8rem;
    font-size: 0.95rem;
}

.post-content {
    color: #635347;
    line-height: 1.8;
    font-size: 1.05rem;
    margin: 2rem 0;
    white-space: pre-line; /* 保留换行格式 */
    padding: 1.5rem;
    background: #fbf7f2; /* 极浅米色内容背景 */
    border-radius: 10px;
}

.post-footer {
    margin-top: 2rem;
    padding-top: 1.5rem;
    border-top: 2px solid #f0e2d4;
    display: flex;
    gap: 1.5rem;
}

.post-footer span {
    color: #8c7465;
    display: flex;
    align-items: center;
    gap: 0.5rem;
    font-size: 0.9rem;
}

.post-footer i {
    color: #d4a88c; /* 柔和的珊瑚色图标 */
}

@media (max-width: 768px) {
    .post-content-container {
        padding: 1.5rem;
        margin: 0 1rem;
    }
    
    h1 {
        font-size: 1.8rem;
    }
}
</style>